package com.javajun.service;

import java.io.IOException;
import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javajun.custom.BaseService;
import com.javajun.douban.DoubanUtils;
import com.javajun.douban.ImageUtil;
import com.javajun.douban.entity.BookJson;
import com.javajun.douban.entity.Result;
import com.javajun.douban.entity.YumImage;
import com.javajun.entity.Book;
import com.javajun.form.BookForm;
import com.javajun.repository.BookRepository;

@Service
public class BookService extends BaseService<Book, Integer>{

    @Autowired
    private BookRepository bookRepository;

    public Book findByIsbn(String isbn) {
        return bookRepository.findByIsbn(isbn);
    }
    
    /**
     * 根據Isbn查找該書是否已存在于數據庫
     * @param isbn
     * @return
     */
    public Boolean repeatIsbn(String isbn) {
        Book book = findByIsbn(isbn);
        Boolean f = false;
        if (book != null) {
            f = true;
        }
        return f;
    }
    
    /**
     * 通过Isbn查找书籍信息
     * @param isbn
     * @return
     */
    public BookJson getBookJson(String isbn) {
        DoubanUtils doubanUtils = new DoubanUtils();
        ObjectMapper mapper = new ObjectMapper();
        Result bookresult = doubanUtils.GetBookInfoByIsbn(isbn);
        BookJson bookJson = new BookJson();
        if (bookresult.getStatusCode() == 200) {
            try {
                bookJson = mapper.readValue(bookresult.getBookJson(), BookJson.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return bookJson;
    }
    
    /**
     * 根据书的Isbn编码返回书的状态，200则表示存在该书
     * @param isbn
     * @return
     */
    public Integer getBookStatusCode(String isbn) {
        DoubanUtils doubanUtils = new DoubanUtils();
        ObjectMapper mapper = new ObjectMapper();
        Result bookresult = doubanUtils.GetBookInfoByIsbn(isbn);
        return bookresult.getStatusCode();
    }
    
    /**
     * 通过传入的 BookJson 新增一本书
     * @param bookJson
     * @param total
     * @return
     */
    public Boolean addBook(BookJson bookJson, Integer total) {
        Boolean f = false;
        Book bookentity = new Book();
        ImageUtil imageUtil = new ImageUtil();
        // 书名
        bookentity.setName(bookJson.getTitle());
        // isbn
        bookentity.setIsbn(bookJson.getIsbn13());
        // 作者
        bookentity.setAuthor(bookJson.getAuthor().toString());
        // 作者简介
        bookentity.setAuthorIntro(bookJson.getAuthorIntro());
        // 目录
        bookentity.setCatalog(bookJson.getCatalog());
        // 出版日期
        bookentity.setPubdate(bookJson.getPubdate());
        // 出版社
        bookentity.setPublisher(bookJson.getPublisher());
        // 总页数
        bookentity.setPages(bookJson.getPages());
        // 定价
        bookentity.setPrice(bookJson.getPrice());
        // 豆瓣链接
        bookentity.setAlt(bookJson.getAlt());
        // 小图
        String smallimage = imageUtil.uploadImg(bookJson.getImages().getSmall()).getRealURL();
        bookentity.setSmallimage(smallimage);
        // 图片
        String image = imageUtil.uploadImg(bookJson.getImage()).getRealURL();
        bookentity.setImage(image);
        // 总数量，若没有总数量，则默认为0
        if (total == null) {
            total = 0;
        }
        bookentity.setTotal(total);
        // 初始借出数量为0
        bookentity.setLend(0);
        try {
            save(bookentity);
            f = true;
        } catch (Exception e) {
            
        }
        return f;
    }
    
    /**
     * 修改书籍数量
     * @param id
     * @param total
     * @return
     */
    public Boolean modifyBook(Integer id, Integer total) {
        Boolean f = false;
        Book entity = findById(id);
        if (total == null) {
            total = 0;
        }
        entity.setTotal(total);
        try {
            save(entity);
            f = true;
        } catch (Exception e) {
        }
        return f;
    }
    
    /**
     * 安全查询
     * @param form
     * @return
     */
    public Specification<Book> buildSpec(BookForm form) {
        Specification<Book> specification = new Specification<Book>() {

            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                HashSet<Predicate> rules=new HashSet<>();
                String isbn = form.getIsbn();
                if(StringUtils.hasText(isbn)) {
                    rules.add(cb.like(root.get("isbn"), "%"+isbn+"%"));
                }
                String name = form.getName();
                if(StringUtils.hasText(name)) {
                    rules.add(cb.like(root.get("name"), "%"+name+"%"));
                }
                String author = form.getAuthor();
                if(StringUtils.hasText(author)) {
                    rules.add(cb.like(root.get("author"), "%"+author+"%"));
                }
                String publisher = form.getPublisher();
                if(StringUtils.hasText(publisher)) {
                    rules.add(cb.like(root.get("publisher"), "%"+publisher+"%"));
                }
                return cb.and(rules.toArray(new Predicate[rules.size()]));
            }
        };
        
        return specification;
        
    }
}
